import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/posts.dart';

class PostsService {
  // 修改为你的后端服务器地址
  static const String baseUrl = 'http://192.168.101.13:8080';
  // 如果在真机上运行，使用：static const String baseUrl = 'http://192.168.1.xxx:8080';

  /// 新增帖子（按后端要求：接收 PostsDTO，返回 Result 包装）
  Future<bool> savePost({
    required String title,
    required String content,
    int? userId,
    String? userName,
    String? imageUrl,
    List<String>? imageUrls,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'title': title,
          'content': content,
          if (userId != null) 'userId': userId,
          // PostsDTO 常见字段：author/userName 二选一，这里传 author
          'author': (userName == null || userName.isEmpty) ? 'username' : userName,
          if (imageUrl != null && imageUrl.isNotEmpty) 'imageUrl': imageUrl,
          if (imageUrls != null && imageUrls.isNotEmpty) 'imageUrls': imageUrls.join(','),
        }),
      );

      if (response.statusCode == 200) {
        // 如果后端使用包装结构，尝试读取 code 判断
        try {
          final map = jsonDecode(response.body) as Map<String, dynamic>;
          final code = map['code'];
          if (code is int) return code == 200 || code == 1 || code == 0;
        } catch (_) {}
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  /// 获取所有帖子
  Future<List<Posts>> getAllPosts() async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        // 支持两种返回：包装结构 or 纯数组
        final data = body is Map<String, dynamic> ? body['data'] : body;
        final list = (data as List).map((e) => Posts.fromJson(e as Map<String, dynamic>)).toList();
        return list;
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }
}


